﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AutoScroll : MonoBehaviour {
    public static bool IsEnabled { get; set; }

    public int cellHeight = 230;
    public int offsetPerFrame = 2;
    public int limitChildCount = 4;
    public bool autoScrollOnAwake = true;

    RectTransform _rt;
    int _total;
    int _activedChildCount;
    

	void Start() {
        _rt = GetComponent<RectTransform>();
        IsEnabled = autoScrollOnAwake;

        var allchilds = _rt.GetComponentsInChildren<UnityEngine.UI.Image>(true);
        _activedChildCount = allchilds.Length;

        for (var i = allchilds.Length - 1; i >= 0; i--) {
            var child = allchilds[i];

            if (child.gameObject.activeInHierarchy == false) {
                Destroy(child.gameObject);
                _activedChildCount -= 1;
            }
        }
    }
	
	void Update() {
        if (IsEnabled == false || _activedChildCount <= limitChildCount) {
            return;
        }

        _rt.anchoredPosition = new Vector2(0f, _rt.anchoredPosition.y + offsetPerFrame);
        _total += offsetPerFrame;

        if (_total % cellHeight == 0) {
            _rt.GetChild(0).SetAsLastSibling();
            _rt.anchoredPosition = Vector2.zero;
            _total = 0;
        }
    }
}
